package rexsee.core.alarm;

import rexsee.core.browser.Browser;
import rexsee.core.browser.clazz.JavascriptInterface;
import rexsee.core.notification.NotificationArgumentsSheet;
import rexsee.core.notification.RexseeNotification;
import rexsee.core.receiver._Receiver;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class RexseeAlarm implements JavascriptInterface {

	public static final String INTERFACE_NAME = "Alarm";
	@Override
	public String getInterfaceName() {
		return mBrowser.application.resources.prefix + INTERFACE_NAME;
	}
	@Override
	public JavascriptInterface getInheritInterface(Browser childBrowser) {
		return this;
	}
	@Override
	public JavascriptInterface getNewInterface(Browser childBrowser) {
		return new RexseeAlarm(childBrowser);
	}

	public static final String ALARM_ACTION = "action.alarm.id_";
	public static final String ALARM_EXTRA_ARGU = "argu";

	public static final String DATABASE_ALARM = "alarm.db";
	public static final String TABLE_ALARM = "alarm";

	private final Context mContext;
	private final Browser mBrowser;

	public RexseeAlarm(Browser browser) {
		mBrowser = browser;
		mContext = browser.getContext();
	}
	public RexseeAlarm(Context context) {
		mBrowser = null;
		mContext = context;
	}

	private static void _setAlarm(Context context, AlarmManager mgr, String body, boolean save) {
		NotificationArgumentsSheet argu = (new NotificationArgumentsSheet()).parseArguments(body);
		if (argu.notificationimmediately) {
			(new RexseeNotification(context)).show(argu);
		}
		if (argu.getAlermFirstTime() > System.currentTimeMillis()) {
			Intent intent = new Intent(context, _Receiver.class);
			intent.setAction(ALARM_ACTION + argu.alermname);
			intent.putExtra(ALARM_EXTRA_ARGU, body);
			PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
			mgr.cancel(pendingIntent);
			long interval = argu.getAlermRepeatInterval();
			if (interval > 0) {
				mgr.setRepeating(AlarmManager.RTC_WAKEUP, argu.getAlermFirstTime(), interval, pendingIntent);
			} else {
				mgr.set(AlarmManager.RTC_WAKEUP, argu.getAlermFirstTime(), pendingIntent);
			}
			if (save) {
				SQLiteDatabase db = context.openOrCreateDatabase(DATABASE_ALARM, Context.MODE_PRIVATE, null);
				try {
					db.execSQL("CREATE TABLE if not exists " + TABLE_ALARM + " (name TEXT, argu TEXT, Primary key(name));");
					db.execSQL("DELETE FROM " + TABLE_ALARM + " WHERE name='" + argu.alermname + "';");
					db.execSQL("INSERT INTO " + TABLE_ALARM + " VALUES ('" + argu.alermname + "', '" + body + "');");
				} catch (Exception e) {
				}
				db.close();
			}
		} else {
			exec(context, body);
		}
	}
	private static void _deleteAlarm(Context context, String name) {
		SQLiteDatabase db = context.openOrCreateDatabase(DATABASE_ALARM, Context.MODE_PRIVATE, null);
		try {
			db.execSQL("DELETE FROM " + TABLE_ALARM + " WHERE name='" + name + "';");
		} catch (Exception e) {
		}
		db.close();
	}

	public static void exec(Context context, String body) {
		NotificationArgumentsSheet argu = (new NotificationArgumentsSheet()).parseArguments(body);
		if (argu.getAlermRepeatInterval() <= 0) {
			_deleteAlarm(context, argu.alermname);
		}
		(new RexseeRemoteCommand(context, body)).exec();
	}
	public static void updateAlarm(Context context) {
		SQLiteDatabase db = context.openOrCreateDatabase(DATABASE_ALARM, Context.MODE_PRIVATE, null);
		AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
		try {
			db.execSQL("CREATE TABLE if not exists " + TABLE_ALARM + " (name TEXT, argu TEXT, Primary key(name));");
			Cursor cursor = db.rawQuery("SELECT * from " + TABLE_ALARM + ";", null);
			if (cursor != null && cursor.getCount() != 0) {
				for (int i = 0; i < cursor.getCount(); i++) {
					cursor.moveToPosition(i);
					_setAlarm(context, mgr, cursor.getString(1), false);
				}
			}
			cursor.close();
		} catch (Exception e) {
		}
		db.close();
	}

	//JavaScript Interface
	public void set(String body) {
		_setAlarm(mContext, (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE), body, true);
	}
	public String get() {
		SQLiteDatabase db = mContext.openOrCreateDatabase(DATABASE_ALARM, Context.MODE_PRIVATE, null);
		String rtn = "";
		try {
			Cursor cursor = db.rawQuery("SELECT * from " + TABLE_ALARM + ";", null);
			if (cursor != null && cursor.getCount() != 0) {
				for (int i = 0; i < cursor.getCount(); i++) {
					cursor.moveToPosition(i);
					if (i > 0) rtn += ",";
					rtn += "{";
					rtn += "\"name\":\"" + cursor.getString(0) + "\"";
					rtn += ",\"argu\":\"" + cursor.getString(1) + "\"";
					rtn += "}";
				}
			}
			cursor.close();
		} catch (Exception e) {
			if (mBrowser != null) mBrowser.exception(getInterfaceName(), e);
		}
		db.close();
		return "[" + rtn + "]";
	}
	public void cancel(String name) {
		Intent intent = new Intent(mContext, _Receiver.class);
		intent.setAction(ALARM_ACTION + name);
		PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
		AlarmManager mgr = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
		mgr.cancel(pendingIntent);
		_deleteAlarm(mContext, name);
	}

	public long getCurrentTime() {
		return System.currentTimeMillis();
	}
	public long getMillisPerHour() {
		return 3600 * 1000;
	}
	public long getMillisPerDay() {
		return 3600 * 1000 * 24;
	}

}
